package com.google.code.coma.gui.rmi;

import com.google.code.coma.Coma;
import com.google.code.coma.domain.Computer;
import com.google.code.coma.gui.DataProvider;
import com.google.code.coma.rmi.ObserveCallback;
import com.google.code.coma.rmi.RMIManager;
import com.google.code.coma.rmi.storage.StorageService;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class RMIComputerDataProvider extends AbstractRMIDataProvider<Computer> implements DataProvider<Computer> {
	private static final Log log = LogFactory.getLog(RMIComputerDataProvider.class);

	private String containerName;

	private ObserveCallback<Computer> callback;

	public RMIComputerDataProvider(String factoryId, String containerName) {
        super(factoryId);
		this.containerName = containerName;
	}

	@Override
	public void bind(final ListView<Computer> computerListView) {
		storageService = RMIManager.getStorageService(factoryId + "_" + containerName);
		try {
			callback = new ObserveCallback<Computer>() {
				@Override
				public void onChange(ChangeAction changeAction, final List<Computer> entries) throws RemoteException {
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							computerListView.setItems(FXCollections.<Computer>observableArrayList(entries));
						}
					});
				}
			};
			storageService.registerObserveCallback((ObserveCallback<Computer>) UnicastRemoteObject.exportObject(callback, 0), ObserveCallback.ChangeAction.values());
		} catch (RemoteException e) {
			log.error(e);
		}
	}

	@Override
	public void shutdown() {

	}
}
